package Thread;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	public static final int PORT = 5678;

	public static void main(String[] args) {
		Server serv = new Server();
		serv.run();
	}

	public void run() {
		try {
			// 创建ServerSocket对象，监听本机的PORT端口
			ServerSocket serverSocket = new ServerSocket(PORT);
			// 创建socket套接字，处理客户端连接请求
			Socket client = serverSocket.accept();
			// 创建缓冲区对象，用于读取客户端发送的信息
			BufferedReader cin = new BufferedReader(new InputStreamReader(
					client.getInputStream()));
			// 创建缓冲区对象，用于向客户端发送信息
			OutputStreamWriter osw = new OutputStreamWriter(client.getOutputStream());
			PrintWriter cout = new PrintWriter(osw);
			// 创建缓冲区对象，用于接受控制台输入
			BufferedReader in = new BufferedReader(new InputStreamReader(
					System.in));
			String message = null, answer = null;
			// 从客户端读取一行信息
			message = cin.readLine();
			// 向客户端发送信息
			while (!"bye".equals(message)) {
				System.out.println("Client say: " + message);
				answer = in.readLine();
				cout.println(answer);
				cout.flush();
				message = cin.readLine();
			}
			System.out.println("Client say: bye");
			cin.close();
			cout.close();
			osw.close();
			client.close();
			serverSocket.close();
		} catch (Exception e) {
			System.out.print("服务器端出错，信息如下：\n" + e.getMessage());
		}
	}

}
